<template>
  <view class="page-warp" v-if="url">
    <web-view :webview-styles="webviewStyles" :src="url" @message="message"></web-view>
  </view>
</template>

<script>
export default {
  onLoad({link, name}) {
    let url = link
    if (!url.includes('http://') && !url.includes('https://')) {
      url = decodeURIComponent(url);
    }
    this.url = url;
    uni.setNavigationBarTitle({
      title: name || ''
    });
  },
  onReady() {
    this.appendJsFile();
  },
  data() {
    return {
      url: '',
      webviewStyles: {
        progress: {
          color: '#FF3333'
        }
      },
      webView: null
    };
  },
  methods: {
    message(e) {
      if (this.url.indexOf(this.api.domain) === 0) {
        var _this = this
        let data = e.detail.data[0];
        eval(data.fn);
      } else {
        let fn = function () {
          alert('暂无权限')
        }
        this.evalWebView(fn)
      }
    },
    evalWebView (js) {
      js = `(${js.toString()})()`
      this.webView.evalJS(js)
    },
    appendJsFile() {
      try {
        // #ifdef APP-PLUS
        var pages = getCurrentPages();
        var page = pages[pages.length - 1];
        setTimeout(() => {
          var currentWebview = page.$getAppWebview();
          this.webView = currentWebview.children()[0];
        }, 0);
        setTimeout(() => {
          if (this.webView) return
          var currentWebview = page.$getAppWebview();
          this.webView = currentWebview.children()[0];
        }, 600);
        // #endif
      } catch (e) {
        this.appendJsFile();
      }
    },
  }
};
</script>

<style></style>
